package com.tceasy.gateway.help;

import com.tceasy.common.utils.date.DateUtils;
import com.tceasy.common.utils.string.StringUtil;
import com.tceasy.gateway.util.ExportExcelUtil;
import org.apache.commons.io.Charsets;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.*;

/**
 * Created by makunpeng on 2017/6/19 0019.
 */

public class ExcelHelp<T> {
	Logger logger = LoggerFactory.getLogger(ExcelHelp.class);
	private Class<T> entityClass;

	public ExcelHelp(Class<T> entityClass) {
		this.entityClass = entityClass;
	}

	public  void dowloadExcel(List<T> datas, String[] columns, String[] columnTxt,String fileName,HttpServletResponse response) throws Exception {
		List<Map> result = getResult(datas,columns);
		Map map = new HashMap();
		map.put("sheetname", DateUtils.formatDatetime(new Date(), "yyyy-MM-dd"));
		String[] headers = columnTxt;
		String[] keys = columns;
		List headlist = new ArrayList();
		map.put("head", headlist);
		map.put("cellnames", headers);
		map.put("cellkey", keys);
		map.put("body", result);
		List taillist = new ArrayList();
		map.put("tail", taillist);
		ExportExcelUtil ex = new ExportExcelUtil();
		HSSFWorkbook hssfWorkbook = ex.exportExcelByMap(map);
		response.setContentType("application/vnd.ms-excel;charset=UTF-8");
		// 2.设置文件头：最后一个参数是设置下载文件名
		 fileName = new String(fileName.getBytes(Charsets.UTF_8), Charsets.ISO_8859_1);
		response.setHeader("Content-Disposition", "attachment;fileName="+fileName+".xls");
		ServletOutputStream outputStream = response.getOutputStream();
		hssfWorkbook.write(outputStream);
	}

	private List<Map> getResult(List<T> datas, String[] columns) throws Exception {
		List<Map> result = new ArrayList<>();
		Method getStrMethod;
		String method = "";
		String fieldValue;
		for(T data :datas){
			Map propertyMap = new HashMap();
			for(String column : columns){
				method = "get" + StringUtil.firstUpper(column);
				getStrMethod = entityClass.getMethod(method);
				fieldValue = (String)getStrMethod.invoke(data);
				propertyMap.put(column,fieldValue);
			}
			result.add(propertyMap);
		}
		return result;
	}
}
